package com.binguo.api.service.local;


import com.binguo.api.baidu.BaiduRecUtil;
import com.binguo.api.baidu.model.ImgTag;
import com.binguo.api.businessmodel.ProductImgDetailModel;
import com.binguo.api.businessmodel.ProductImgModel;
import com.binguo.api.data.CacheData;
import com.binguo.api.form.ProductCorrectForm;
import com.binguo.api.form.ProductCorrectItemForm;
import com.binguo.api.response.localrec.GetIPResponseVO;
import com.binguo.api.response.product.ProductRecResultDetailVONewWithLocation;
import com.binguo.api.response.product.ProductRecResultVONewWithLocation;
import com.binguo.api.result.Result;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.common.util.ImageUtil;
import com.binguo.common.util.JsonUtil;
import com.binguo.common.util.LoggerUtil;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.File;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static com.binguo.api.data.CacheData.ipAddress;

@Component
public class LocalService {

    private static Logger logger = LoggerFactory.getLogger(LocalService.class);
    @Resource
    private ShopLocalIpMapper shopLocalIpMapper;
    @Resource
    private CashierDeskMapper cashierDeskMapper;

    @Resource
    private BranchMapper branchMapper;

    @Resource
    private ShopProductMessageMapper shopProductMessageMapper;

    @Resource
    LogProductRecMapper logProductRecMapper;

    @Resource
    ProductMapper productMapper;

    @Resource
    LogProductImgMapper logProductImgMapper;

    @Resource
    BaiduRecUtil baiduRecUtil;

    public RestTemplate restTemplate = new RestTemplate();

    public String imgPath = "/usr/local/nginx/html";

    public List<ShopProductMessage> getMessageList(Integer branchId){
        Condition condition = new Condition(ShopProductMessage.class);
        condition.or().andEqualTo("branchId", branchId).andEqualTo("readState", 0);
        List<ShopProductMessage> list = shopProductMessageMapper.selectByCondition(condition);

        if (list != null && list.size() > 0) {
            List<Integer> idList = list.stream().map(ShopProductMessage::getId).collect(Collectors.toList());

            ShopProductMessage temp = new ShopProductMessage();
            temp.setReadState(1);
            Condition updateCondition = new Condition(ShopProductMessage.class);
            updateCondition.or().andIn("id", idList);
            shopProductMessageMapper.updateByConditionSelective(temp, updateCondition);
        }
        return list;
    }

    public boolean correctProductImg(ProductCorrectForm productCorrectForm) {


        if (productCorrectForm.getItemList() == null || productCorrectForm.getItemList().size() == 0) {
            return false;
        }

        logger.info("===============start =====correctProductImg");
        try {
            ProductImgModel productImgModel = baiduRecUtil.getProductImgFromCache(productCorrectForm.getProductOrderNo());

            if (productImgModel == null) {
                Condition condition = new Condition(ProductImgJsonInfo.class);
                condition.or().andEqualTo("productOrderNo", productCorrectForm.getProductOrderNo());
                List<ProductImgJsonInfo> productImgJsonInfoList = baiduRecUtil.productImgJsonInfoMapper.selectByCondition(condition);
                if (productImgJsonInfoList != null && productImgJsonInfoList.size() > 0){
                    String content = productImgJsonInfoList.get(0).getProductContent();
                    productImgModel = JsonUtil.parse(content, ProductImgModel.class);
                }else {
                    return false;
                }
            }

            if (productImgModel.getItemList() != null && productImgModel.getItemList().size() > 0) {
                int i = 0;

                Map<Integer, ProductImgDetailModel> productImgDetailModelMap = new HashMap<>();

                Map<Integer, ProductCorrectItemForm> productCorrectItemFormHashMap = new HashMap<>();


                for (ProductCorrectItemForm productCorrectItemForm : productCorrectForm.getItemList()) {
                    productCorrectItemFormHashMap.put(productCorrectItemForm.getSeq(), productCorrectItemForm);
                }

                for (ProductImgDetailModel productImgDetailModel : productImgModel.getItemList()) {
                    ProductCorrectItemForm productCorrectItemForm = productCorrectItemFormHashMap.get(productImgDetailModel.getSeq());

                    if (productCorrectItemForm != null) {

                        productImgDetailModel.setProductName(productCorrectItemForm.getProductName());
                        productImgDetailModel.setProductId(productCorrectItemForm.getProductId());

                        productImgDetailModelMap.put(productImgDetailModel.getSeq(), productImgDetailModel);
                    }
                }

                List<Integer> productIdList = null;
                if(DataLoadService.shopYpProductListMap != null) {
                    List<ProductYpRef> temp = DataLoadService.shopYpProductListMap.get(productImgModel.getShopId());

                    if (temp != null && temp.size() > 0) {
                        productIdList = temp.stream().map(ProductYpRef::getProductId).collect(Collectors.toList());
                    }
                }

                for (ProductCorrectItemForm productCorrectItemForm : productCorrectForm.getItemList()) {
                    if (productIdList != null && productIdList.contains(productCorrectItemForm.getProductId())) {
                        logger.info("忽略云澎菜品库商品:" + productCorrectItemForm.getProductName());
                        continue;
                    }

                    ProductImgDetailModel productImgDetailModel = productImgDetailModelMap.get(productCorrectItemForm.getSeq());

                    Integer productId = productCorrectItemForm.getProductId();

                    String localFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId() + "/" + productId;

                    File imgCutFile = new File(localFilepath);
                    if (!imgCutFile.exists()) {
                        imgCutFile.mkdir();
                    }
                    localFilepath += "/temp";

                    File imgCutFileTemp = new File(localFilepath);
                    if (!imgCutFileTemp.exists()) {
                        imgCutFileTemp.mkdir();
                    }

                    StringBuffer cutImgUrl = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/img/")
                            .append(productImgModel.getShopId())
                            .append("/")
                            .append(productId)
                            .append("/temp/")
                            .append(productImgModel.getUuidFileName())
                            .append("_cut")
                            .append(i)
                            .append(".png");

                    String cutImgPath = localFilepath + "/" + productImgModel.getUuidFileName() + "_cut" + i + ".png";
                    i++;

                    String sourceFilePath = productImgModel.getSourceFilename();
                    String sourceFilePathOnNet = productImgModel.getSourceImgOnInternet();
                    if (productImgModel.getCurIpAddress() != null &&
                            productImgModel.getCurIpAddress().equals(ipAddress)
                            ) {
                        LoggerUtil.console.info("upload correct source file ip : {}, sourceFilePath:", productImgModel.getCurIpAddress(), sourceFilePath);
                    } else {
                        LoggerUtil.console.info("upload correct source file ip : {}", productImgModel.getCurIpAddress());

                        String downloadNetFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId() + "/" + productId + "/net";

                        File downloadNetFilepathFile = new File(downloadNetFilepath);
                        if (!downloadNetFilepathFile.exists()) {
                            downloadNetFilepathFile.mkdir();
                        }

                        int tempInt = new Random(100).nextInt();
                        downloadNetFilepath += "/" + productImgModel.getUuidFileName() + "." + tempInt + ".png";
                        ImageBase64Util.downloadNetImage(productImgModel.getSourceImgOnInternet(), downloadNetFilepath);

                        LoggerUtil.console.info("source file ip : {}, sourceFilePath:{}",
                                productImgModel.getCurIpAddress(), downloadNetFilepath);
                        sourceFilePath = downloadNetFilepath;

                        StringBuffer temp = new StringBuffer("http://")
                                .append(ipAddress)
                                .append(":8019/img/")
                                .append(productImgModel.getShopId())
                                .append("/")
                                .append(productId)
                                .append("/net/")
                                .append(productImgModel.getUuidFileName())
                                .append(".")
                                .append(tempInt)
                                .append(".png");

                        sourceFilePathOnNet = temp.toString();
                    }

                    ImageUtil.cutImage(sourceFilePath, cutImgPath
                            , productImgDetailModel.getLeft(),
                            productImgDetailModel.getTop(), productImgDetailModel.getWidth(), productImgDetailModel.getHeight());

                    logger.info("===============cutImgPath==" + cutImgPath);

                    Integer branchId = null;
                    Product p = productMapper.selectByPrimaryKey(productId);
                    if (p != null) {
                        branchId = p.getStoreid();
                        LogProductImg logProductImgFromUser = new LogProductImg();
                        logProductImgFromUser.setBranchId(branchId);
                        logProductImgFromUser.setProductId(productId);
                        logProductImgFromUser.setCreateTime(new Date());
                        logProductImgFromUser.setCutImg(cutImgPath);
                        logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                        logProductImgFromUser.setShopId(productImgModel.getShopId());
                        logProductImgFromUser.setBaiduDeleted(0);
                        logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                        logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);

                        logProductImgMapper.insert(logProductImgFromUser);
                    }
                    return true;
                }
            }
        } catch (Exception e) {

        }

        return false;
    }

    public void uploadRecResult(LogProductRec logProductRec, ProductRecResultVONewWithLocation productRecResultVONewWithLocation) throws Exception{

        logProductRecMapper.insert(logProductRec);

        if (productRecResultVONewWithLocation != null) {
            productRecResultVONewWithLocation.getProductOrderNo();

            ProductImgModel productImgModel = new ProductImgModel();
            productImgModel.setProductOrderNo(productRecResultVONewWithLocation.getProductOrderNo());
            productImgModel.setShopId(logProductRec.getShopId());
            productImgModel.setSourceFilename(logProductRec.getFilepath());
            productImgModel.setUuidFileName(productRecResultVONewWithLocation.getProductOrderNo());
            productImgModel.setImgUrl(logProductRec.getImgSrcNetUrl());
            productImgModel.setCurIpAddress(ipAddress);
            productImgModel.setSourceImgOnInternet(logProductRec.getImgSrcNetUrl());
            productImgModel.setItemList(new ArrayList<>());


            List<ProductRecResultDetailVONewWithLocation> productList = productRecResultVONewWithLocation.getProductList();

            if (productList != null && productList.size() > 0) {
                List<ImgTag> imgTagList = new ArrayList<>();
                for (ProductRecResultDetailVONewWithLocation temp : productList) {
                    ImgTag imgTag = new ImgTag();
                    imgTag.setX1(temp.getX1());
                    imgTag.setX2(temp.getX2());
                    imgTag.setY1(temp.getY1());
                    imgTag.setY2(temp.getY2());
                    imgTag.setLabel(temp.getSeq() + "、" + temp.getProductName());
                    imgTag.setScore(temp.getConfident());

                    imgTagList.add(imgTag);

                    ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                    productImgDetailModel.setProductName(temp.getProductName());
                    productImgDetailModel.setProductId(temp.getProductId());
                    productImgDetailModel.setSeq(temp.getSeq());
                    productImgDetailModel.setLeft(temp.getX1());
                    productImgDetailModel.setTop(temp.getY1());
                    if (temp.getX2() > temp.getX1()) {
                        productImgDetailModel.setWidth(temp.getX2() - temp.getX1());
                    }else {
                        productImgDetailModel.setWidth(temp.getX1() - temp.getX2());
                    }

                    if (temp.getY2() > temp.getY1()) {
                        productImgDetailModel.setHeight(temp.getY2() - temp.getY1());
                    }else {
                        productImgDetailModel.setHeight(temp.getY1() - temp.getY2());
                    }
                    productImgDetailModel.setScore(1);

                    productImgModel.getItemList().add(productImgDetailModel);
                }

                baiduRecUtil.setKey(productImgModel.getProductOrderNo(), productImgModel, 60 * 60 * 1000);

                ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                productImgJsonInfo.setProductContent(JsonUtil.toJson(productImgModel));
                productImgJsonInfo.setProductOrderNo(productImgModel.getProductOrderNo());

                baiduRecUtil.productImgJsonInfoMapper.insert(productImgJsonInfo);

                String imgJson = JsonUtil.toJson(imgTagList);

                logger.info("imgJson==" + imgJson);
                String temp = Base64.getEncoder().encodeToString(imgJson.getBytes());
                logger.info(temp);

                imgJson = URLEncoder.encode(temp);
                logger.info(imgJson);

                long endTime2 = System.currentTimeMillis();

                String tempOutputFilepath = logProductRec.getOutputFilepath().replaceAll(imgPath, "/data/html");
                String tempFilename = logProductRec.getFilepath().replaceAll(imgPath, "/data/html");

                String drwaImgParam = "outputFilepath=" + tempOutputFilepath + "&filename=" + tempFilename + "&image=" + imgJson;

                HttpEntity drawEntity = new HttpEntity<>(drwaImgParam, CacheData.DEFAULT_JSON_HEADER);

                ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://" + CacheData.recIp +":8082/hello2", drawEntity, String.class);

                logger.info(drwaImgResult.getBody());


                long endTime3 = System.currentTimeMillis();
                logger.info("endTime4=" + endTime3 + ",画框时间 intelval=" + (endTime3 - endTime2));

                if ("ok".equals(drwaImgResult.getBody())) {

                }
            }
        }

    }

    public Result getIpList(String curIp, String deviceId, Integer branchId) {
        Result result = new Result();
        GetIPResponseVO responseVO = new GetIPResponseVO();
        Integer shopId = null;
        if (branchId != null && branchId > 0) {
            Condition cashierDeskCondition = new Condition(CashierDesk.class);
            cashierDeskCondition.setOrderByClause(" created desc");
            cashierDeskCondition.or().andEqualTo("ccode", deviceId)
                    .andEqualTo("deleted", false)
            ;
            List<CashierDesk> cashierDeskList = cashierDeskMapper.selectByCondition(cashierDeskCondition);

            if (cashierDeskList != null && cashierDeskList.size() > 0) {
                for (CashierDesk cashierDesk : cashierDeskList) {
                    if (cashierDesk != null) {
                        shopId = cashierDesk.getShopid();
                        if (cashierDesk.getBranchid() != null && cashierDesk.getBranchid() > 0) {
                            branchId = cashierDesk.getBranchid();
                        }else {
                            Condition branchCondition = new Condition(Branch.class);
                            branchCondition.or().andEqualTo("shopId", cashierDesk.getShopid());
                            List<Branch> branchList = branchMapper.selectByCondition(branchCondition);
                            if (branchList != null && branchList.size() == 1) {
                                branchId = branchList.get(0).getBranchId();
                            }
                        }
                    }
                }
            }
        }

        responseVO.setBranchId(branchId);
        responseVO.setShopId(shopId);

        if (branchId != null && branchId > 0) {
            Condition condition = new Condition(ShopLocalIp.class);
            condition.or().andEqualTo("branch_id", branchId);

            List<ShopLocalIp> shopLocalIpList = shopLocalIpMapper.selectByCondition(condition);

            if (shopLocalIpList != null && shopLocalIpList.size() > 0) {

                List<String> ipList = null;
                int searchCount = 1;
                for (ShopLocalIp shopLocalIp : shopLocalIpList) {
                    if (shopLocalIp.getDeviceId() != null && shopLocalIp.getDeviceId().equals(deviceId)) {
                        if (shopLocalIp.getIp() != null && shopLocalIp.getIp().equals(curIp)) {
                            continue;
                        }else {
                            ShopLocalIp temp = new ShopLocalIp();
                            temp.setId(shopLocalIp.getId());
                            temp.setDeviceId(deviceId);

                            shopLocalIpMapper.updateByPrimaryKeySelective(temp);
                        }
                    }else {
                        searchCount++;
                        if (shopLocalIp.getIp() != null) {
                            if (ipList == null) {
                                ipList = new ArrayList<>();
                            }
                            ipList.add(shopLocalIp.getIp());
                        }
                    }
                }

                if (searchCount == shopLocalIpList.size()) {
                    //not found handler

                    Condition branchCondition = new Condition(Branch.class);
                    branchCondition.or().andEqualTo("branchId", branchId);
                    List<Branch> branchList = branchMapper.selectByCondition(branchCondition);
                    ShopLocalIp shopLocalIp = new ShopLocalIp();
                    if (branchList != null && branchList.size() > 0) {
                        shopLocalIp.setShopId(branchList.get(0).getShopId());
                    }
                    shopLocalIp.setDeviceId(deviceId);
                    shopLocalIp.setIp(curIp);
                    shopLocalIp.setBranchId(branchId);

                    shopLocalIpMapper.insertSelective(shopLocalIp);
                }

                responseVO.setIpList(ipList);

            }
        }

        result.setData(responseVO);

        return result;
    }
}
